package org.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;
import java.util.Map;

@RestController
public class Actrl {

    // 示例1: 带路径参数的Mono响应
    @GetMapping("/user/{id}")
    public Mono<String> getUserById(@PathVariable String id) {
        return Mono.just("User-" + id);
    }

    // 示例2: 带请求参数的Flux响应
    @GetMapping("/items")
    public Flux<String> getItems(@RequestParam int count) {
        return Flux.range(1, count)
                .map(i -> "Item-" + i);
    }

    // 示例3: 模拟异步数据流（带延迟）
    @GetMapping("/stream")
    public Flux<String> dataStream() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(tick -> "Event-" + tick)
                .take(5); // 只发送5个元素
    }

    // 示例4: 错误处理（Mono）
    @GetMapping("/error-demo")
    public Mono<String> errorDemo(@RequestParam(required = false) String key) {
        return Mono.justOrEmpty(key)
                .switchIfEmpty(Mono.error(new ResponseStatusException(
                        HttpStatus.BAD_REQUEST, "Missing parameter 'key'")
                ))
                .map(k -> "Processed: " + k);
    }

    // 示例5: 组合多个Mono操作
    @GetMapping("/combine")
    public Mono<String> combineOperations(@RequestParam String first,
                                          @RequestParam String second) {
        return Mono.just(first)
                .zipWith(Mono.just(second))
                .map(tuple -> tuple.getT1() + " + " + tuple.getT2());
    }

    // 示例6: 响应式JSON对象（Mono<Map>）
    @GetMapping("/user-info")
    public Mono<Map<String, Object>> getUserInfo() {
        return Mono.just(Map.of(
                "name", "Reactor",
                "age", 28,
                "skills", List.of("Java", "Reactive")
        ));
    }

    @GetMapping("/user-info22")
    public Mono<JSONObject> getUserInfo22() {
        JSONObject jsonObject = JSON.parseObject("{\n" +
                "  \"name\": \"tom\"\n" +
                "}");
        return Mono.just(jsonObject);
    }

    // 示例7: 从外部服务获取Flux数据（模拟）
    @GetMapping("/external-data")
    public Flux<Map<String, String>> fetchExternalData() {
        return Flux.just(
                Map.of("id", "1", "value", "Data1"),
                Map.of("id", "2", "value", "Data2"),
                Map.of("id", "3", "value", "Data3")
        ).delayElements(Duration.ofMillis(300));
    }

    // 示例8: POST请求体处理（Mono）
    @PostMapping("/create")
    public Mono<ItemRequest> createItem(@RequestBody Mono<ItemRequest> request) {
        return request
                .flatMap(Mono::just);
    }

    // 示例9: 响应式文件下载（简化版）
    @GetMapping("/download")
    public Flux<byte[]> downloadFile() {
        byte[] data = "Reactive File Content".getBytes();
        return Flux.just(data);
    }

    // 示例10: 流式数据库查询结果（模拟）
    @GetMapping("/db-records")
    public Flux<String> streamFromDatabase() {
        return Flux.fromIterable(List.of("Record-1", "Record-2", "Record-3"))
                .concatWithValues("END");
    }
}

// DTO类用于示例8
